<script lang="ts">
import { defineComponent } from "vue";
import { ElCollapse, ElCollapseItem } from "element-plus";
import { ElMessage } from "element-plus";

export default {
  exportProps: {
    // formData: Object,
  },

  // sendDataToParent() {
  //   // 在这里触发名为 'send-data' 的自定义事件，并传递数据
  //   //this.$emit("setBlameFormData", props.formData?.subject, formData);
  // },
  methods: {
    save() {
      // 在这里编写保存逻辑，可以是将表单数据提交给后端或进行其他保存操作
      console.log("Saving BlameView data");
    },
  },
};
</script>

<script lang="ts" setup>
import { useRouter } from "vue-router";
import {
  reactive,
  ref,
  defineProps,
  defineExpose,
  getCurrentInstance,
  onMounted,
  watch,
} from "vue";
const instance = getCurrentInstance();
const { $http } = instance?.appContext.config.globalProperties as any;
const props = defineProps({
  userId: {
    type: String,
    required: true,
  },
  subject: {
    type: String,
    required: false,
  },
  formReadOnly: {
    type: Boolean,
    required: false,
  },
  formData: {
    type: Object,
    required: true,
  },
});

const form: { [key: string]: any } = ref({
  design_eval_impl_uid: "",
  subject: "",
  introducer_id: "",
  introducer_name: "",
  content: "",
  reason: "",
  reason_other: "",
  judge: "",
  replier_id: "",
  replier_name: "",
  measure: "",
  plan_completion_node: "",
  plan_completion_node_other: "",
  progress: "",
  confirmation: "",
  confirmation_reason: "",
});

const selectedUserName = ref({});
const userSelecterLoading = ref(false);

interface ListItem {
  value: string;
  label: string;
  validValue: string;
  userInfo: UserInfo;
}

interface UserInfo {
  userId: string;
  userName: string;
  displayName: string;
  pinyin: string;
}

const itemList = ref<ListItem[]>([]);
const users = ref<UserInfo[]>([]);
const selecterOptions = ref<ListItem[]>([]);
const createrEditable = ref(false);
const replierEditable = ref(false);

watch(
  () => props.userId,
  async (newUserId: string) => {
    if (newUserId) {
      initUser(newUserId);
    }
  }
);
// watch(
//   () => props.subject,
//   async (newSubject: string) => {
//     if (newSubject) {
//       form.subject = newSubject;
//     }
//   }
// );

watch(form, (newValue, oldValue) => {
  //Compare current form data with initial data to detect modifications
  //console.log("表单被修改了", oldValue, newValue);
  //sendDataToParent();
});

watch(selectedUserName, (newValue, oldValue) => {
  form.value.replier_name = newValue;
  const us = users.value.filter((item) => {
    return (
      form.value.replier_name &&
      form.value.replier_name.localeCompare(item.displayName) == 0
    );
  });
  console.log("filter user = ", us);
  if (us && us.length > 0) {
    form.value.replier_id = us[0].userId;
  } else {
    form.value.replier_id = "";
  }

  console.log("new form = ", form.value);
});

const sendDataToParent = () => {
  console.log("同步到主页");
  // 在这里触发名为 'setBlameFormData' 的自定义事件，并传递数据
  instance?.emit("setBlameFormData", form.value.subject, form);
};

onMounted(() => {
  initUser(props.userId);
  // form.subject = props.subject;
});

const initUser = (userId: string) => {
  form.value.introducer_id = userId;
  $http
    .get("/getUserNameById?userId=" + userId)
    .then((response: { data: any }) => {
      console.log("查询结果", response.data);
      form.value.introducer_name =
        response.data + " (" + form.value.introducer_id + ")";
    });
};

const initUserList = async () => {
  try {
    if (itemList.value == null || itemList.value.length == 0) {
      const response = await $http.get("/getAllUsers");
      users.value = response.data;
      userSelecterLoading.value = false;
      itemList.value = users.value.map((item): ListItem => {
        return {
          value: `${item.displayName}`,
          label: `${item.displayName}`,
          validValue: `${item.displayName}` + item.pinyin,
          userInfo: item,
        };
      });
    }
  } catch (error) {
    console.error(error);
    ElMessage({
      type: "error",
      message: error,
    });
  }
};

const userSelecterRemoteMethod = async (query: string) => {
  if (query !== "") {
    //userSelecterLoading.value = true;
    try {
      await initUserList();
      selecterOptions.value = itemList.value.filter((item) => {
        return item.validValue.toLowerCase().includes(query.toLowerCase());
      });
    } catch (error) {
      console.error(error);
      ElMessage({
        type: "error",
        message: error,
      });
    }

    // setTimeout(() => {
    //   loading.value = false;
    //   options.value = list.filter((item) => {
    //     return item.label.toLowerCase().includes(query.toLowerCase());
    //   });
    // }, 200);
  } else {
    selecterOptions.value = [];
  }
};

const activeNames = ref(["1"]);
const handleChange = (val: string[]) => {
  console.log(val);
};
const submit = () => {
  console.log("submit!");
};
const getFormData = () => {
  // 已经通过watch更新form信息了
  // if (selectedUserName.value) {
  //   console.log(selectedUserName.value);
  //   //form.value.replier_name = selectedUser.value.userInfo.displayName;
  //   form.value.replier_name = selectedUserName.value;
  // }
  return form.value;
};
const setFormData = async (data: any, userId: string) => {
  console.log("setFormData ==>", data);
  /**
   * 当前的访问者
   * 如果是指摘提出者，则可以编辑提出者编辑部分
   * 如果是指摘回复者，则可以编辑回复者编辑部分
   */
  if (userId && userId === data.introducer_id) {
    createrEditable.value = true;
  } else {
    createrEditable.value = false;
  }
  if (userId && userId === data.replier_id) {
    replierEditable.value = true;
  } else {
    replierEditable.value = false;
  }
  if (data.replier_id) {
    await initUserList();
    console.log("用户信息初始化完成");
    const f = itemList.value.filter((item) => {
      return item.userInfo.userId == data.replier_id;
    });
    console.log("匹配用户信息 ==> ", f);
    if (f && f.length > 0) {
      selectedUserName.value = f[0].value;
    }
  } else {
    selectedUserName.value = "";
  }
  form.value = data;
};
defineExpose({
  submit,
  getFormData,
  setFormData,
});
</script>
<template>
  <el-form
    :model="form"
    label-width="auto"
    label-position="left"
    style="max-width: 600px"
    :disabled="props.formReadOnly"
  >
    <el-form-item label="指摘提出者">
      <el-input v-model="form.introducer_name" prefix-icon="User" readonly />
    </el-form-item>
    <el-divider content-position="center">提出者填写</el-divider>
    <el-form-item label="指摘主题">
      <el-input
        v-model="form.subject"
        :readonly="!createrEditable"
        :class="{ 'read-only-input': !createrEditable }"
      />
    </el-form-item>
    <el-form-item label="指摘内容">
      <el-input
        v-model="form.content"
        rows="4"
        type="textarea"
        :readonly="!createrEditable"
        :class="{ 'read-only-input': !createrEditable }"
      />
    </el-form-item>
    <el-form-item label="指摘要因" :disabled="!createrEditable">
      <el-radio-group v-model="form.reason">
        <el-radio label="设计" value="设计" name="reason"></el-radio>
        <el-radio label="制造" value="制造" name="reason"></el-radio>
        <el-radio label="其它" value="其它" name="reason"></el-radio>
      </el-radio-group>
      <el-input
        v-model="form.reason_other"
        :readonly="!createrEditable"
        :class="{ 'read-only-input': !createrEditable }"
      />
    </el-form-item>
    <el-form-item label="指摘判断">
      <el-radio-group v-model="form.judge" :disabled="!createrEditable">
        <el-radio label="×" value="×" name="judge"></el-radio>
        <el-radio label="△" value="△" name="judge"></el-radio>
        <el-radio label="□" value="□" name="judge"></el-radio>
        <el-radio label="确认" value="确认" name="judge"></el-radio>
      </el-radio-group>
    </el-form-item>
    <el-divider
      content-position="center"
      :readonly="!createrEditable"
      :class="{ 'read-only-input': !createrEditable }"
      >提出者填写</el-divider
    >
    <el-divider border-style="dashed">
      <el-icon><star-filled /></el-icon>
    </el-divider>
    <el-divider content-position="center">技术员填写</el-divider>
    <el-form-item label="指摘回复者">
      <!-- <el-input v-model="form.replier" /> -->
      <el-select-v2
        v-model="selectedUserName"
        style="width: 240px"
        filterable
        remote
        :remote-method="userSelecterRemoteMethod"
        clearable
        :options="selecterOptions"
        :loading="userSelecterLoading"
        placeholder="请输入或选择用户"
        :readonly="!createrEditable"
        :class="{ 'read-only-input': !createrEditable }"
      >
      </el-select-v2>
    </el-form-item>
    <el-form-item label="指摘对策">
      <el-input
        v-model="form.measure"
        :readonly="!replierEditable"
        :class="{ 'read-only-input': !replierEditable }"
      />
    </el-form-item>
    <el-form-item label="计划完成节点">
      <el-radio-group
        v-model="form.plan_completion_node"
        :disabled="!replierEditable"
      >
        <el-radio label="DR1" value="DR1" name="productLevel"></el-radio>
        <el-radio label="DR2" value="DR2" name="productLevel"></el-radio>
        <el-radio label="出图" value="出图" name="productLevel"></el-radio>
        <el-radio label="量产" value="量产" name="productLevel"></el-radio>
        <el-radio label="出货" value="出货" name="productLevel"></el-radio>
        <el-radio label="其他" value="其他" name="productLevel"></el-radio>
      </el-radio-group>
      <el-input
        v-model="form.plan_completion_node_other"
        :readonly="!replierEditable"
        :class="{ 'read-only-input': !replierEditable }"
      />
    </el-form-item>
    <el-form-item label="指摘对应状况">
      <el-radio-group v-model="form.progress" :disabled="!replierEditable">
        <el-radio label="对策完了" value="对策完了" name="progress"></el-radio>
        <el-radio label="对策中" value="对策中" name="progress"></el-radio>
        <el-radio
          label="对策未着手"
          value="对策未着手"
          name="progress"
        ></el-radio>
      </el-radio-group>
    </el-form-item>
    <el-divider content-position="center">技术员填写</el-divider>
    <el-divider border-style="dashed">
      <el-icon><star-filled /></el-icon>
    </el-divider>
    <el-divider content-position="center">提出者填写</el-divider>
    <el-form-item label="对策确认" :disabled="!createrEditable">
      <el-radio-group v-model="form.confirmation">
        <el-radio label="OK" value="OK" name="productLevel"></el-radio>
        <el-radio label="NG" value="NG" name="productLevel"></el-radio>
      </el-radio-group>
      <el-input
        v-model="form.confirmation_reason"
        placeholder="理由"
        :readonly="!createrEditable"
        :class="{ 'read-only-input': !createrEditable }"
      />
    </el-form-item>
    <el-divider content-position="center">提出者填写</el-divider>
  </el-form>
</template>

<style>
.text-left {
  text-align: left;
  width: 15px;
}
.read-only-input .el-input__inner {
  background-color: #f5f5f5;
}
.read-only-input .el-input__wrapper {
  background-color: #f5f5f5;
}
</style>
